package com.ruoyi.mushcoin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryTable;
import com.mybatisflex.core.query.QueryWrapper;
import com.ruoyi.common.core.utils.MapstructUtils;
import com.ruoyi.common.orm.core.page.PageQuery;
import com.ruoyi.common.orm.core.page.TableDataInfo;
import com.ruoyi.common.orm.core.service.impl.BaseServiceImpl;
import com.ruoyi.mushcoin.domain.TgUserInfo;
import com.ruoyi.mushcoin.domain.bo.TgUserInfoBo;
import com.ruoyi.mushcoin.domain.vo.TgUserInfoVo;
import com.ruoyi.mushcoin.mapper.TgUserInfoMapper;
import com.ruoyi.mushcoin.service.ITgUserInfoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

import static com.ruoyi.mushcoin.domain.table.TgUserInfoTableDef.TG_USER_INFO;

/**
 * TG用户Service业务层处理
 *
 * @author billy
 * 2024-07-29
 */
@Service
@Slf4j
public class TgUserInfoServiceImpl extends BaseServiceImpl<TgUserInfoMapper, TgUserInfo> implements ITgUserInfoService {
    @Resource
    private TgUserInfoMapper tgUserInfoMapper;

    @Override
    public QueryWrapper query() {
        return super.query().from(TG_USER_INFO);
    }

    private QueryWrapper buildQueryWrapper(TgUserInfoBo tgUserInfoBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(TG_USER_INFO.USER_ID.eq(tgUserInfoBo.getUserId()));
        queryWrapper.and(TG_USER_INFO.FIRST_NAME.like(tgUserInfoBo.getFirstName()));
        queryWrapper.and(TG_USER_INFO.LAST_NAME.like(tgUserInfoBo.getLastName()));
        queryWrapper.and(TG_USER_INFO.USER_NAME.like(tgUserInfoBo.getUserName()));
        queryWrapper.and(TG_USER_INFO.IS_PREMIUM.eq(tgUserInfoBo.getIsPremium()));
        queryWrapper.and(TG_USER_INFO.INVITE_USER_ID.eq(tgUserInfoBo.getInviteUserId()));
        queryWrapper.and(TG_USER_INFO.CURRENCY_OF_EXCHANGE.eq(tgUserInfoBo.getCurrencyOfExchange()));
        if (StringUtils.isNotBlank(tgUserInfoBo.getAddress())) {
            queryWrapper.and(String.format("t2.address like '%%%s%%'", tgUserInfoBo.getAddress()));
        }
        return queryWrapper;
    }


    /**
     * 查询TG用户
     *
     * @param id TG用户主键
     * @return TG用户
     */
    @Override
    public TgUserInfoVo selectById(Long id) {
        return this.getOneAs(query().where(TG_USER_INFO.ID.eq(id)), TgUserInfoVo.class);

    }

    /**
     * 查询TG用户列表
     *
     * @param tgUserInfoBo TG用户Bo
     * @return TG用户集合
     */
    @Override
    public List<TgUserInfoVo> selectList(TgUserInfoBo tgUserInfoBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(tgUserInfoBo);
        return this.listAs(queryWrapper, TgUserInfoVo.class);
    }

    /**
     * 分页查询TG用户列表
     *
     * @param tgUserInfoBo TG用户Bo
     * @return 分页TG用户集合
     */
    @Override
    public TableDataInfo<TgUserInfoVo> selectPage(TgUserInfoBo tgUserInfoBo) {

        log.info("TgUserInfoServiceImpl: 测试--> Dloader.path");

        QueryWrapper queryWrapper = buildQueryWrapper(tgUserInfoBo);
        queryWrapper.select("user.id,user.user_id,user.first_name,user.last_name,user.user_name,user.is_premium,user.is_premium_tg,user.country_code,user.mushcoin,user.invite_user_id,user.invite_rewards_total,user.create_time,user.update_time"
            , "user.invite_user_count,user.save_game_count,user.vip_end_time"
            , "(user.mushcoin + user.invite_rewards_total) all_mushcoin"
            , "t2.address"
            , """
                game_data->>'$."user-currency"."1"' gold,CAST(game_data->>'$."user-currency"."2"' AS SIGNED) diamond,game_data->>'$."user-currency"."201"' rankCoin
                """
            , "t3.ip_address,t3.ip_address_name,t3.mobile_device_name"
        );
        queryWrapper.from(TgUserInfo.class).as("user");
        queryWrapper.leftJoin(new QueryTable("tg_user_wallet_address").as("t2")).on("user.user_id=t2.user_id");
        queryWrapper.leftJoin(new QueryTable("tg_user_detail").as("t3")).on("user.user_id=t3.user_id");
        Page<TgUserInfoVo> page = this.pageAs(PageQuery.build(), queryWrapper, TgUserInfoVo.class);
        return TableDataInfo.build(page);
    }

    /**
     * 邀请数据表
     *
     * @param tgUserInfoBo TG用户Bo
     * @return
     */
    @Override
    public TableDataInfo<TgUserInfoVo> inviteUserRewardsPage(TgUserInfoBo tgUserInfoBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(tgUserInfoBo);
        //queryWrapper.select("id,user_id,first_name,last_name,user_name,is_premium,mushcoin,tui.invite_user_id,create_time,update_time,invite_user_count"
        //    , """
        //        ifnull(iu.gold,0) gold,ifnull(iu.diamond,0) diamond,ifnull(iu.mush,0) mush,ifnull(iu.totalReward,0) invite_rewards_total
        //        """);
        //Page<TgUserInfoVo> page = this.pageAs(PageQuery.build(), queryWrapper, TgUserInfoVo.class);

        Page<TgUserInfoVo> page = PageQuery.build();
        page.setRecords(tgUserInfoMapper.inviteUserRewardsPage(queryWrapper));
        return TableDataInfo.build(page);
    }

    /**
     * 新增TG用户
     *
     * @param tgUserInfoBo TG用户Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(TgUserInfoBo tgUserInfoBo) {
        TgUserInfo tgUserInfo = MapstructUtils.convert(tgUserInfoBo, TgUserInfo.class);


        return this.save(tgUserInfo);//使用全局配置的雪花算法主键生成器生成ID值
    }

    /**
     * 新增TG用户，前台提供主键值，一般用于导入的场合
     *
     * @param tgUserInfoBo TG用户Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(TgUserInfoBo tgUserInfoBo) {
        TgUserInfo tgUserInfo = MapstructUtils.convert(tgUserInfoBo, TgUserInfo.class);


        return tgUserInfoMapper.insertWithPk(tgUserInfo) > 0;//前台传来主键值
    }

    /**
     * 修改TG用户
     *
     * @param tgUserInfoBo TG用户Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(TgUserInfoBo tgUserInfoBo) {
        TgUserInfo tgUserInfo = MapstructUtils.convert(tgUserInfoBo, TgUserInfo.class);
        if (ObjectUtil.isNotNull(tgUserInfo) && ObjectUtil.isNotNull(tgUserInfo.getId())) {
            boolean updated = this.updateById(tgUserInfo);
            return updated;
        }
        return false;
    }


    /**
     * 批量删除TG用户
     *
     * @param ids 需要删除的TG用户主键集合
     * @return 结果:true 删除成功，false 删除失败
     */
    @Transactional
    @Override
    public boolean deleteByIds(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    public TgUserInfo getUserInfoByIdEasy(Long userId) {
        QueryWrapper query = new QueryWrapper();
        query.select("id, user_id, first_name, last_name, user_name, language_code, is_premium, mushcoin" +
            ", create_time, update_time, invite_user_id, invite_rewards_total, currency_of_exchange, vip_end_time");
        query.where("user_id=" + userId);
        return this.getOne(query);
    }
}
